package com.yyk.yykywd.mvvm.ui

import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import com.orhanobut.logger.Logger
import com.yyk.yykywd.*
import com.yyk.yykywd.base.BaseActivity
import com.yyk.yykywd.bean.BaseBean
import com.yyk.yykywd.config.HttpUrl
import com.yyk.yykywd.mvvm.adapter.ImageViewAdapter
import com.yyk.yykywd.mvvm.entity.HospitalDetailBean
import com.yyk.yykywd.mvvm.event.FinishWorkDetail
import com.yyk.yykywd.mvvm.view_model.WorkDetailViewModel
import com.yyk.yykywd.util.DensityUtils
import com.yyk.yykywd.util.GlideUtils
import com.yyk.yykywd.util.ToAnotherActivity
import com.yyk.yykywd.util.ToastUtil
import com.yyk.yykywd.widght.SpaceItemDecoration
import kotlinx.android.synthetic.main.activity_agent_refund.*
import kotlinx.android.synthetic.main.activity_work_detail.*
import kotlinx.android.synthetic.main.layout_load.*
import kotlinx.android.synthetic.main.rl_bottom1.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class WorkDetailActivity : BaseActivity() {
    private lateinit var viewModel: WorkDetailViewModel
    private lateinit var licenceAdapter: ImageViewAdapter
    private lateinit var surveyAdapter: ImageViewAdapter
    private lateinit var permitAdapter: ImageViewAdapter

    override fun initView() {
        EventBus.getDefault().register(this)
        viewModel = ViewModelProviders.of(this).get(WorkDetailViewModel::class.java)
        with(viewModel) {
            id = intent.getStringExtra(ID)
            type = intent.getStringExtra(TYPE)
            flag = intent.getIntExtra(FLAG, 0)
            showType = intent.getIntExtra(SHOW_TYPE, 0)
            typeS = intent.getIntExtra(TYPE_S, 0)
        }
        setBackArrow()
        when (viewModel.type) {
            FROM_CUSTOMER_RETURN_MONEY_AGENT -> {
                setTitle("全款合同详情")
                cl_agent.visibility = View.VISIBLE
                cl_hospital.visibility = View.GONE
                cl_all_bottom.visibility = View.GONE
                cl_contract_info.visibility = View.VISIBLE
                cl_hos_contract_info.visibility = View.GONE
                iv.setImageResource(R.drawable.icon_dls1)
                notShowThrowOpenSeaTime()
            }
            FROM_INSTALL_HOSPITAL -> {
                setTitle("安装医院详情")
                cl_agent.visibility = View.GONE
                cl_hospital.visibility = View.VISIBLE
                cl_all_bottom.visibility = View.GONE
                cl_contract_info.visibility = View.GONE
                cl_hos_contract_info.visibility = View.VISIBLE

                notShowThrowOpenSeaTime()
            }
            FROM_POTENTIAL_CUSTOMER_AGENT, FROM_POTENTIAL_CUSTOMER_HOSPITAL -> {
                setPotentialLayout(viewModel.type)
                notShowThrowOpenSeaTime()
            }
            FROM_SIGN_CONTRACT_HOSPITAL -> {
                setTitle("签订合同详情")
                if (viewModel.showType == 1) {
                    cl_all_bottom.visibility = View.VISIBLE
                } else {
                    cl_all_bottom.visibility = View.GONE
                }
                cl_agent.visibility = View.GONE
                cl_hospital.visibility = View.VISIBLE
                cl_bottom1.visibility = View.GONE
                cl_bottom2.visibility = View.GONE
                cl_bottom3.visibility = View.GONE
                cl_bottom4.visibility = View.GONE
                cl_bottom.visibility = View.VISIBLE
                cl_contract_info.visibility = View.GONE
                cl_hos_contract_info.visibility = View.VISIBLE
                tv_add.text = "业务跟进"
                tv_save.text = "安装完成"

                viewModel.detail = 1

                notShowThrowOpenSeaTime()
            }
            FROM_C_CUSTOMER_AGENT -> {
                setTitle("C类客户详情")
                if (viewModel.showType == 1) {
                    cl_all_bottom.visibility = View.VISIBLE
                } else {
                    cl_all_bottom.visibility = View.GONE
                }
                cl_agent.visibility = View.VISIBLE
                cl_hospital.visibility = View.GONE
                cl_bottom1.visibility = View.GONE
                cl_bottom2.visibility = View.GONE
                cl_bottom3.visibility = View.GONE
                cl_bottom4.visibility = View.VISIBLE
                cl_bottom.visibility = View.GONE
                cl_contract_info.visibility = View.GONE
                cl_hos_contract_info.visibility = View.GONE

                viewModel.detail = 2

                notShowThrowOpenSeaTime()
            }
            FROM_C_CUSTOMER_HOSPITAL -> {
                setTitle("C类客户详情")
                if (viewModel.showType == 1) {
                    cl_all_bottom.visibility = View.VISIBLE
                } else {
                    cl_all_bottom.visibility = View.GONE
                }
                cl_agent.visibility = View.GONE
                cl_hospital.visibility = View.VISIBLE
                cl_bottom1.visibility = View.GONE
                cl_bottom2.visibility = View.GONE
                cl_bottom3.visibility = View.GONE
                cl_bottom4.visibility = View.VISIBLE
                cl_bottom.visibility = View.GONE
                cl_contract_info.visibility = View.GONE
                cl_hos_contract_info.visibility = View.GONE

                viewModel.detail = 1

                notShowThrowOpenSeaTime()
            }
            FROM_CUSTOMER_OPEN_SEA_HOSPITAL -> {
                setTitle("公海客户")
                cl_all_bottom.visibility = View.VISIBLE
                cl_bottom1.visibility = View.GONE
                cl_bottom2.visibility = View.GONE
                cl_bottom3.visibility = View.VISIBLE
                cl_bottom4.visibility = View.GONE
                cl_bottom.visibility = View.GONE

                cl_agent.visibility = View.GONE
                cl_hospital.visibility = View.VISIBLE
                cl_contract_info.visibility = View.GONE
                cl_hos_contract_info.visibility = View.GONE
                showThrowOpenSeaTime()
            }
            FROM_CUSTOMER_OPEN_SEA_AGENT -> {
                setTitle("公海客户")
                cl_all_bottom.visibility = View.VISIBLE
                cl_bottom1.visibility = View.GONE
                cl_bottom2.visibility = View.GONE
                cl_bottom3.visibility = View.VISIBLE
                cl_bottom4.visibility = View.GONE
                cl_bottom.visibility = View.GONE

                cl_agent.visibility = View.VISIBLE
                cl_hospital.visibility = View.GONE
                cl_contract_info.visibility = View.GONE
                cl_hos_contract_info.visibility = View.GONE
                showThrowOpenSeaTime()
            }
        }

        rv_business_licence.layoutManager = GridLayoutManager(mActivity, 5)
        rv_business_licence.addItemDecoration(SpaceItemDecoration(DensityUtils.dp2px(mActivity, 10f)))
        licenceAdapter = ImageViewAdapter(mActivity, R.layout.item_iv, viewModel.licences)
        rv_business_licence.adapter = licenceAdapter

        rv_survey_form.layoutManager = GridLayoutManager(mActivity, 5)
        rv_survey_form.addItemDecoration(SpaceItemDecoration(DensityUtils.dp2px(mActivity, 10f)))
        surveyAdapter = ImageViewAdapter(mActivity, R.layout.item_iv, viewModel.surveyForm)
        rv_survey_form.adapter = surveyAdapter

        rv_permit.layoutManager = GridLayoutManager(mActivity, 5)
        rv_permit.addItemDecoration(SpaceItemDecoration(DensityUtils.dp2px(mActivity, 10f)))
        permitAdapter = ImageViewAdapter(mActivity, R.layout.item_iv, viewModel.permit)
        rv_permit.adapter = permitAdapter

    }

    override fun initData() {
        loading_layout.showLoading()
        viewModel.getReturnMoneyDetail()
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_work_detail
    }

    override fun setListener() {
        super.setListener()
        cl_business_process_tracking.setOnClickListener {
            var t = ""
            with(viewModel.type) {
                if (this == FROM_CUSTOMER_RETURN_MONEY_AGENT ||
                        this == FROM_POTENTIAL_CUSTOMER_AGENT ||
                        this == FROM_C_CUSTOMER_AGENT ||
                        this == FROM_CUSTOMER_OPEN_SEA_AGENT) {
                    t = "2"
                } else {
                    t = "1"
                }
            }
            val url = String.format(HttpUrl.BUSINESS_PROCESS_TRACKING, viewModel.id, t)
            ToAnotherActivity.toWebActivity(mActivity, url, "业务流程跟踪")
        }
        surveyAdapter.setOnItemClickListener { _, _, position ->
            ToAnotherActivity.toPicActivity(mActivity, HttpUrl.BASE_URL + viewModel.surveyForm[position])
        }
        licenceAdapter.setOnItemClickListener { _, _, position ->
            ToAnotherActivity.toPicActivity(mActivity, HttpUrl.BASE_URL + viewModel.licences[position])
        }
        permitAdapter.setOnItemClickListener { _, _, position ->
            ToAnotherActivity.toPicActivity(mActivity, HttpUrl.BASE_URL + viewModel.permit[position])
        }

        iv_id_front.setOnClickListener {
            ToAnotherActivity.toPicActivity(mActivity, HttpUrl.BASE_URL + viewModel.idFront)
        }

        iv_id_back.setOnClickListener {
            ToAnotherActivity.toPicActivity(mActivity, HttpUrl.BASE_URL + viewModel.idBack)
        }

        tv_business_follow.setOnClickListener {
            ToAnotherActivity.toBusinessFollowActivity(mActivity,
                    viewModel.type,
                    viewModel.id,
                    viewModel.visitorName,
                    viewModel.visitorPosition,
                    viewModel.visitorPhone)
        }
        tv_add.setOnClickListener {
            ToAnotherActivity.toBusinessFollowActivity(mActivity,
                    viewModel.type,
                    viewModel.id,
                    viewModel.visitorName,
                    viewModel.visitorPosition,
                    viewModel.visitorPhone)
        }

        tv_business_follow2.setOnClickListener {
            ToAnotherActivity.toBusinessFollowActivity(mActivity,
                    viewModel.type,
                    viewModel.id,
                    viewModel.visitorName,
                    viewModel.visitorPosition,
                    viewModel.visitorPhone)
        }

        tv_business_follow3.setOnClickListener {
            ToAnotherActivity.toBusinessFollowActivity(mActivity,
                    viewModel.type,
                    viewModel.id,
                    viewModel.visitorName,
                    viewModel.visitorPosition,
                    viewModel.visitorPhone)
        }
        tv_business_follow4.setOnClickListener {
            ToAnotherActivity.toBusinessFollowActivity(mActivity,
                    viewModel.type,
                    viewModel.id,
                    viewModel.visitorName,
                    viewModel.visitorPosition,
                    viewModel.visitorPhone)
        }

        tv_upload_contract.setOnClickListener {
            toUploadContract()
        }

        tv_upload_contract4.setOnClickListener {
            toUploadContract()
        }

        tv_throw.setOnClickListener {
            addSeas(mActivity) {
                viewModel.setC(THROW)
            }
        }
        tv_throw4.setOnClickListener {
            addSeas(mActivity) {
                viewModel.setC(THROW)
            }
        }

        tv_set_c.setOnClickListener {
            show(mActivity, "是否确认操作？",
                    "C类客户为无明确业务意向客户，转入后不可转回，但客户仍属于你，可在\"工作-C类客户\"中跟进此客户",
                    "确认",
                    "取消") {
                viewModel.setC(SET_C)
            }
        }

        tv_save.setOnClickListener {
            show(mActivity, "是否确认已安装影像设备？",
                    "确认后该条业务将完结，可在\"业务统计——安装医院列表\"中查看",
                    "确认",
                    "取消") {
                viewModel.setC(INSTALL_COMPLETE)
            }
        }

//        tv_completion_contract.setOnClickListener {
//            ToAnotherActivity.toCompletionContractActivity(mActivity, viewModel.id)
//        }

        viewModel.agentDetail.observe(this, Observer {
            iv.setImageResource(R.drawable.icon_dls1)
            it.data?.run {
                viewModel.amountCollected = already_money.toString()
                tv_number.text = operation_num
                tv_return_money_status.text = tag_client
                if (add_gh_day == 0) {
                    tv_days.text = "于今晚24:00流至公海"
                } else {
                    tv_days.text = add_gh_day.toString() + "天"
                }
                if (belong_type == 2) {
                    tv_founder_lint.text = "业务认领人"
                    tv_founder.text = claimname
                    tv_create_time_lint.text = "从公海认领时间"
                    tv_create_time.text = getCommonTime(update_time)
                } else {
                    tv_founder_lint.text = "业务创建人"
                    tv_founder.text = addname
                    tv_create_time_lint.text = "创建时间"
                    tv_create_time.text = getCommonTime(create_time)
                }
                tv_throw_sea_time.text = getCommonTime(cast_time)
                if (ptype == 1) {
                    tv_agent_type.text = "个人"
                    viewModel.isPerson = true
                    tv_id_photo_lint.text = "代理商身份证照片"
                    tv_business_licence_lint.visibility = View.GONE
                    rv_business_licence.visibility = View.GONE
                } else {
                    tv_agent_type.text = "公司"
                    viewModel.isPerson = false
                    tv_id_photo_lint.text = "法人身份证照片"
                    tv_business_licence_lint.visibility = View.VISIBLE
                    rv_business_licence.visibility = View.VISIBLE
                }
                tv_agent_name.text = agentname
                tv_contact.text = phone
                tv_agent_region.text = area
                tv_agent_source.text = source
                if (trade.isNullOrBlank()) {
                    tv_agent_industry_lint.visibility = View.GONE
                    tv_agent_industry.visibility = View.GONE
                } else {
                    tv_agent_industry_lint.visibility = View.VISIBLE
                    tv_agent_industry.visibility = View.VISIBLE
                    tv_agent_industry.text = trade
                }
                if (desc.isNullOrBlank()) {
                    tv_agent_describe_lint.visibility = View.GONE
                    tv_agent_describe.visibility = View.GONE
                } else {
                    tv_agent_describe_lint.visibility = View.VISIBLE
                    tv_agent_describe.visibility = View.VISIBLE
                    tv_agent_describe.text = desc
                }
            }
            it.info?.run {
                if (flag == 2) {
                    tv_contract_hint.visibility = View.VISIBLE
                    if (viewModel.typeS == 1) {
                        cl_all_contract.visibility = View.VISIBLE
                        with(it.info2) {
                            tv_all_contact_type.text = getContractType(flag)
                            tv_all_contact_num.text = order_code_1
                            for (p in pic) {
                                viewModel.allContracts.add(p.path)
                            }
                        }
                    }
                } else {
                    tv_contract_hint.visibility = View.GONE
                    cl_all_contract.visibility = View.GONE
                }
                tv_agent_site_type.text = status
                tv_agent_price.text = agency_money.toString()
                tv_contact_type.text = getContractType(flag)
                tv_contact_num.text = order_code

                for (photo in pic) {
                    val path = photo.path
                    when (photo.type) {
                        1 -> {
                            viewModel.contracts.add(path)
                        }
                        2 -> {
                            viewModel.idFront = path
                        }
                        3 -> {
                            viewModel.idBack = path
                        }
                        4 -> {
                            viewModel.licences.add(path)
                        }
                        5 -> {
                            viewModel.surveyForm.add(path)
                        }
                        6 -> {
                            viewModel.permit.add(path)
                        }
                    }
                }
            }

            GlideUtils.loadRoundCircleImage(mActivity, HttpUrl.BASE_URL + viewModel.idFront, iv_id_front, 4)
            GlideUtils.loadRoundCircleImage(mActivity, HttpUrl.BASE_URL + viewModel.idBack, iv_id_back, 4)
            licenceAdapter.notifyDataSetChanged()

            loading_layout.showContent()
            nv.visibility = View.VISIBLE
        })

        viewModel.error.observe(this, Observer {

        })

        tv_contract_img.setOnClickListener {
            ToAnotherActivity.toContractImgActivity(mActivity, viewModel.contracts)
        }
        tv_hos_contract_img.setOnClickListener {
            ToAnotherActivity.toContractImgActivity(mActivity, viewModel.contracts)
        }
        tv_all_contract_img.setOnClickListener {
            ToAnotherActivity.toContractImgActivity(mActivity, viewModel.allContracts)
        }

        viewModel.hospitalDetail.observe(this, Observer<HospitalDetailBean> {
            iv.setImageResource(R.drawable.icon_yy1)
            it.data?.run {
                tv_return_money_status.text = tag_client
                if (belong_type == 2) {
                    tv_founder_lint.text = "业务认领人"
                    tv_founder.text = claimname
                    tv_create_time_lint.text = "从公海认领时间"
                    tv_create_time.text = getCommonTime(update_time)
                } else {
                    tv_founder_lint.text = "业务创建人"
                    tv_founder.text = addname
                    tv_create_time_lint.text = "创建时间"
                    tv_create_time.text = getCommonTime(create_time)
                }
                tv_throw_sea_time.text = getCommonTime(cast_time)
                tv_number.text = operation_num
                tv_hospital_name.text = hos_name
                tv_hospital_type.text = type_name
                tv_hospital_level.text = grade_name
                tv_visit_time.text = getCommonTimeWithYMD(call_time)
                tv_visitor_name.text = call_name
                tv_visitor_position.text = call_grade
                tv_visitor_phone.text = call_phone
                tv_hospital_situation.text = hos_text
                if (add_gh_day == 0) {
                    tv_days.text = "于今晚24:00流至公海"
                } else {
                    tv_days.text = add_gh_day.toString() + "天"
                }
            }
            it.info?.run {
                tv_hos_site_type.text = status
                tv_hos_contact_num.text = order_code
                for (photo in pic) {
                    val path = photo.path
                    when (photo.type) {
                        1 -> {
                            viewModel.contracts.add(path)
                        }
                        2 -> {
                            viewModel.idFront = path
                        }
                        3 -> {
                            viewModel.idBack = path
                        }
                        4 -> {
                            viewModel.licences.add(path)
                        }
                        5 -> {
                            viewModel.surveyForm.add(path)
                        }
                        6 -> {
                            viewModel.permit.add(path)
                        }
                    }
                }

                if (viewModel.permit.isEmpty()) {
                    rv_permit.visibility = View.GONE
                    tv_medical_lint.visibility = View.GONE
                } else {
                    rv_permit.visibility = View.VISIBLE
                    tv_medical_lint.visibility = View.VISIBLE
                    permitAdapter.notifyDataSetChanged()
                }
                surveyAdapter.notifyDataSetChanged()
            }
            loading_layout.showContent()
            nv.visibility = View.VISIBLE
        })

        viewModel.base.observe(this, Observer<BaseBean> {
            ToastUtil.showShort(it.msg)
            if (it.code == 200) {
                finish()
            }
        })

        tv_claim.setOnClickListener {
            ToAnotherActivity.toClaimCustomerActivity(mActivity, viewModel.id, viewModel.type)
        }
    }

    private fun toUploadContract() {
        Logger.e(viewModel.type)
        if (viewModel.type == FROM_POTENTIAL_CUSTOMER_HOSPITAL ||
                viewModel.type == FROM_C_CUSTOMER_HOSPITAL) {
            ToAnotherActivity.toUploadContractActivity(mActivity, FROM_HOSPITAL_UPLOAD, viewModel.id)
        } else {
            if (viewModel.isPerson) {
                ToAnotherActivity.toUploadContractActivity(mActivity, FROM_AGENT_PERSONAL_UPLOAD, viewModel.id)
            } else {
                ToAnotherActivity.toUploadContractActivity(mActivity, FROM_AGENT_COMPANY_UPLOAD, viewModel.id)
            }
        }
    }

    private fun setPotentialLayout(type: String) {
        setTitle("意向客户详情")
        if (viewModel.showType == 1) {
            cl_all_bottom.visibility = View.VISIBLE
        } else {
            cl_all_bottom.visibility = View.GONE
        }
        if (type == FROM_POTENTIAL_CUSTOMER_HOSPITAL) {
            cl_agent.visibility = View.GONE
            cl_hospital.visibility = View.VISIBLE
            viewModel.detail = 1
        } else {
            cl_agent.visibility = View.VISIBLE
            cl_hospital.visibility = View.GONE
            viewModel.detail = 2
        }
        cl_contract_info.visibility = View.GONE
        cl_hos_contract_info.visibility = View.GONE
        cl_bottom1.visibility = View.VISIBLE
        cl_bottom2.visibility = View.GONE
        cl_bottom3.visibility = View.GONE
        cl_bottom4.visibility = View.GONE
        cl_bottom.visibility = View.GONE
    }

    private fun showThrowOpenSeaTime() {
        tv_throw_sea_time_hint.visibility = View.VISIBLE
        tv_throw_sea_time.visibility = View.VISIBLE
        tv_days_hint.visibility = View.GONE
        tv_days.visibility = View.GONE
    }

    private fun notShowThrowOpenSeaTime() {
        tv_throw_sea_time_hint.visibility = View.GONE
        tv_throw_sea_time.visibility = View.GONE
        tv_days_hint.visibility = View.VISIBLE
        tv_days.visibility = View.VISIBLE
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun finishDetail(event: FinishWorkDetail) {
        finish()
    }
}
